<?php

/*
 * Created on May 12, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Ncategory extends MY_Controller {
    
    function __construct() {

        parent::__construct();

        $this->checkLogin();
        $this->buildMenu();
        $this->load->model('ncategory_model', 'ncategory', true);
        $this->template->set_master_template('admin_master_template');
    }

    function index() {
        //echo $this->config->item('language');
        //$this->main = '<div> erer erer er </div>';
        //$this->execute();
        //$this->load->view('main', '');
        $this->view();
        // echo 'aasa';
    }

    function create() {
        $data = array();

        $obj = new stdClass();
        /* $obj->id_ncategory = 0;
          $obj->id_parent_ncategory = 0;
          $obj->vi_name = '';
          $obj->en_name = '';
          $obj->vi_description = '';
          $obj->en_description = '';

          $obj->link_rewrite = '';
          $obj->meta_title = '';
          $obj->meta_keywords = '';
          $obj->meta_description = '';
          $obj->level_depth = 0;
          $obj->active = 1;

          $obj->date_add = date('Y-m-d H:i:s', time());
          $obj->date_upd = date('Y-m-d H:i:s', time());
         */
        $data['id_ncategory'] = 0;
        $data['id_parent_ncategory'] = 0;
        $data['vi_name'] = '';
        $data['en_name'] = '';
        $data['vi_description'] = '';
        $data['en_description'] = '';
        $data['link_rewrite'] = '';
        $data['meta_title'] = '';
        $data['meta_keywords'] = '';
        $data['meta_description'] = '';
        $data['level_depth'] = 0;
        $data['active'] = 1;
        $data['date_add'] = date('Y-m-d H:i:s', time());
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $data['position'] = 1;
        //$data['category'] = $obj;
        $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', 0);
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_news_category');
        //$this->main = $this->load->view('admin/ncategory/create_ncategory', $data, true);
        //$this->execute();
        $this->template->parse_view('content', 'admin/ncategory/create_ncategory', $data);
        $this->template->render();
    }

    function edit($id) {
        $category = $this->ncategory->getById($id);

        if (!$category) {
            redirect('admin/ncategory/view');
        }

        $data = $category;
        $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $category['id_parent_ncategory']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('edit_news_category');
        //$this->main = $this->load->view('admin/ncategory/create_ncategory', $data, true);
        //$this->execute();
        $this->template->parse_view('content', 'admin/ncategory/create_ncategory', $data);
        $this->template->render();
    }

    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('file')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }

    function view($id_parent = 0, $page = 0) {
        $this->load->library('pagination');

        //$id_parent = $this->uri->segment(4, 0);

        //$page = (int) $this->uri->segment(5);

        $config['base_url'] = site_url('admin/ncategory/view/' . $id_parent . '/');

        $config['total_rows'] = $this->ncategory->getCountAllAdmin($id_parent);
        $config['per_page'] = NUMBER_RECORD_PER_PAGE;
        $config['uri_segment'] = 4;
        $config['first_link'] = 'First';

        $this->pagination->initialize($config);

        //$paging = $this->pagination->create_links();
        //$this->setTemplate(array ('admin/ncategory/ncategory_list.tpl'));
        //$items = $this->loadItems();
        $items = '';
        $pcategories = $this->ncategory->getAllAdmin($id_parent, $page, NUMBER_RECORD_PER_PAGE);

        if ($page > 0 AND count($pcategories) == 0) {
            //redirect('admin/ncategory/view/' . ($page - NUMBER_RECORD_PER_PAGE));
           // return;
        }

        //$this->setTemplate(array ('admin/ncategory/ncategory_item.tpl'));
        /* for($i = 0; $i < count($pcategories); $i++){
          $id = $pcategories[$i]->id_ncategory;
          $name = $pcategories[$i]->vi_name;
          $description = $pcategories[$i]->vi_description;
          $parent = $pcategories[$i]->id_parent_ncategory;

          $items .= eval ($this->loadTemplate('admin/ncategory/ncategory_item.tpl'));
          }
         */
        $data = array('rows' => $pcategories);
        //$this->main = $this->load->view('admin/ncategory/ncategory_list', $data, true); //eval ($this->loadTemplate('admin/ncategory/ncategory_list.tpl'));
        //$this->execute();
        //$data['items'] = $items;
        $this->template->parse_view('content', 'admin/ncategory/ncategory_list', $data);
        $this->template->render();
        // echo 'call view.';
    }

    function buidDDProductCategoryList($name, $default) {

        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->ncategory->getAll(0, 0, -1);
        //$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space = '';
        $label = 'Parent';
        $class = '';
        $action = '';
        $style = '';

        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->id_parent_ncategory][$category->id_ncategory] = $category;
        }
        //print_r($tmp);
        //$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, 0, $default);
        $options = $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true) . $this->getCategoryOption($tmp/* $categories */, 0, $default);
        //return eval($this->loadTemplate('admin/ddl.tpl'));
        $data = array();
        $data['name'] = $name;
        $data['style'] = $style;
        $data['class'] = $class;
        $data['action'] = $action;
        $data['options'] = $options;
        return $this->load->view('admin/select', $data, true);
    }

    function getCategoryOption($tmp/* $categories */, $parent = 0, $default = 0, $space = '&nbsp;') {
        $items = '';

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->id_ncategory;
                $value = $v->id_ncategory;
                $label = $v->vi_name;
                $selected = '';
                if ($value == $default)
                    $selected = 'selected';
                //$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
                $items .= $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true);
                $items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function save() {
        //$this->setTemplate('form_new_ncategory.tpl');
        $txtID = (int) trim($this->input->post('txtID'));
        $txtCode = trim($this->input->post('txtCode'));
        $txtLinkRewrite = trim($this->input->post('txtLinkRewrite'));
        $category = null;
        if ($txtID > 0){
            $category = $this->ncategory->getById($txtID);
            $data = $category;
        }
        else {
            
            $data['id_ncategory'] = 0;
            //$category->code = '';
            $data['link_rewrite'] = '';
            $data['id_parent_ncategory'] = (int) trim($this->input->post('parent'));
        }

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');
        /*
          if(($txtCode!=$category->code AND $txtID > 0) OR $txtID==0){
          $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]|callback_code_check');
          //echo $txtCode.' '.$category->code; return;
          }else
          $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]');
         */
        //$this->form_validation->set_rules('parent', 'lang:parent_code', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
        if ($txtLinkRewrite != '' AND $txtLinkRewrite != $category['link_rewrite'])
            $this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
        /* $this->form_validation->set_rules('password', 'Password', 'required');
          $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
          $this->form_validation->set_rules('email', 'Email', 'required');
         */


        if (!$category AND $txtID > 0) {
            redirect('admin/ncategory/view');
            return;
        }

        //$category->code = trim($this->input->post('txtCode'));
        $data['id_parent_ncategory'] = (int) trim($this->input->post('parent'));
        
        $data['vi_name'] = trim($this->input->post('txtViName'));
        $data['en_name'] = trim($this->input->post('txtEnName'));
        $data['vi_description'] = trim($this->input->post('txtViDescription'));
        $data['en_description'] = trim($this->input->post('txtEnDescription'));
        $data['meta_description'] = trim($this->input->post('txtMetaDescription'));
        $data['link_rewrite'] = trim($this->input->post('txtLinkRewrite'));
        $data['meta_title'] = trim($this->input->post('txtMetaTitle'));
        $data['meta_keywords'] = trim($this->input->post('txtMetaKeywords'));
        $data['active'] = (int) $this->input->post('active');
        $data['position'] = trim($this->input->post('position'));
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
        $category_parent = ''; //$this->buidDDNewsCategoryList('ddlParentCategory', 0);



        if ($this->form_validation->run() == FALSE) {
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);
            //$data = array();
            $data['category'] = $category;
            $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $category['id_parent_ncategory']);
            $data['error_message'] = '<div style="color:red">' . validation_errors() . '</div>';
            //if()
            $data['legend_text'] = $txtID > 0 ? lang('edit_news_category') : lang('create_news_category');
            //$this->main = $this->load->view('admin/ncategory/create_ncategory', $data, true);
            //$this->execute();
            $this->template->parse_view('content', 'admin/ncategory/create_ncategory', $data);
            $this->template->render();
            return;
        } else {
            //$parent_cat = $this->pcategory->getByCode($category->code_parent);
            //$category->id_parent_pcategory = $parent_cat->id_pcategory;
            if ($txtID > 0) {
                $result = $this->ncategory->update($data);
            } else {
                $data['level_depth'] = 0;
                $data['date_add'] = date('Y-m-d H:i:s', time());
                $data['position'] = $this->ncategory->getMaxPosition() + 1;
                $result = $this->ncategory->create($data);
            }

            redirect('admin/ncategory/view');
        }
    }

    function code_check($code) {
        $result = $this->ncategory->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function friendly_url_check($url) {
        $result = $this->ncategory->getByLinkRewrite($url);
        if ($result != null) {
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function testGetFile() {
        $config = array(
            'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
            'max_size' => 1024000000 /* 1Mb */
        );

        $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');

        if (!$result['error'])
            echo 'Get file success.';
        else
            echo $result['message'];
    }

    function delete() {
        $id = intval($this->uri->segment(4));
        $ids = array();
        if ($id > 0) {
            $ids[] = $id;
        } else {
            if (($this->input->post('submitDelcategory'))) {
                $ids = $this->input->post('categoryBox');
            }
        }

        $categories = $this->ncategory->getAll(0, 0, -1);
        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->id_parent_ncategory][$category->id_ncategory] = $category;
        }

        $ids_delete = array();

        for ($i = 0; $i < count($ids); $i++) {
            $ids_delete[] = $ids[$i];
            $ids_delete = array_merge($ids_delete, $this->helpDelete($tmp, $ids[$i]));
        }

        $this->ncategory->delete($ids_delete);
        //print_r($ids_delete);
        redirect('admin/ncategory');
    }

    function helpDelete($tmp/* $categories */, $parent = 0) {
        $result = array();

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                $parent = $v->id_ncategory;
                $result[] = $v->id_ncategory;

                $result = array_merge($result, $this->helpDelete($tmp/* $categories */, $parent));
            }
        }

        return $result;
    }
    
    function change_order() {
        $id1 = (int) $this->uri->segment(4);
        $id2 = (int) $this->uri->segment(5);

        $cat1 = $this->ncategory->getById($id1);
        $cat2 = $this->ncategory->getById($id2);

        if ($cat1 AND $cat2) {
            $position1 = $cat1['position'];
            $cat1['position'] = $cat2['position'];
            $cat2['position'] = $position1;

            $this->ncategory->update($cat1);
            $this->ncategory->update($cat2);
        }

        redirect('admin/ncategory');
    }

}

?>
